<template>
  <van-row gutter="20" class="tc tt br1">
    <van-col span="10">商品名</van-col>
    <van-col span="6">价钱（p）</van-col>
    <van-col span="8">数量</van-col>
  </van-row>
  <van-row class="tl tr" v-for="(item, index) in goods">
    <van-col span="10" class="br1 bt1 bl0"
      ><div class="tc fcc">{{ item.name }}</div>
    </van-col>
    <van-col span="6" class="br1 bt1 bl0"
      ><div class="fcc">{{ item.price }} / {{ item.unit }}</div></van-col
    >
    <van-col span="8" class="br1 bt0 bl0 fcc"
      ><div class="fcc">
        <van-stepper min="0" max="999" theme="round" v-model="item.count" /></div
    ></van-col>
    <van-field v-if="item.count > 0" class="vfi" v-model="item.memo" placeholder="请输入备注" />
  </van-row>
  <div class="tb">
    <span v-if="goods.length == 0">提示：可选商品为空，请先前往商品管理页面</span>
  </div>
  <div v-if="goods.length > 0">总价：{{ totalPrize }}，总数量：{{ totalCount }}</div>
</template>
<script setup>
  import { ref, onBeforeUnmount, unref, computed } from "vue";
  import { useRouter } from "vue-router";
  import { showToast } from "vant";
  const router = useRouter();
  const pureGoods = JSON.parse(router?.currentRoute?.value?.params?.pureGoods || "[]");
  const info = JSON.parse(router?.currentRoute?.value?.params?.info || "{}");
  const goods = ref([]);
  getGoods();

  const totalPrize = computed(() => {
    return goods.value.reduce((p, it) => {
      return p + (it.count || 0) * (it.price || 0);
    }, 0);
  });

  const totalCount = computed(() => {
    return goods.value.reduce((p, it) => {
      return p + (it.count || 0);
    }, 0);
  });

  function getGoods() {
    const goodsString = localStorage.getItem("goods");
    if (goodsString) {
      const arr = JSON.parse(goodsString);
      arr.forEach((o) => {
        const it = pureGoods.find((it) => it.name == o.name);
        o.count = it?.count || 0;
        o.memo = it?.memo || "";
      });
      goods.value = arr;
    }
  }

  function purePickGoods() {
    return goods.value.filter((o) => o.count > 0);
  }

  window.win_info_back = null;
  window.win_pick_submit = function submit() {
    const pureGoods = purePickGoods();
    if (pureGoods.length == 0) {
      return showToast("请选购商品");
    }
    router.replace({
      name: "info",
      path: "/info",
      params: { pureGoods: JSON.stringify(unref(pureGoods)), info: JSON.stringify(info) },
    });
  };
  window.win_goods_back = function () {
    goods.value.forEach((it) => (it.count = 0));
  };
  onBeforeUnmount(() => {
    window.win_pick_submit = null;
  });
</script>
<style scoped>
  .bt1 {
    border-left: 1px solid #ccc;
    position: relative;
  }
  .bl0 {
    border-left: 0;
  }
  .bdem {
    position: absolute;
    bottom: 2px;
    right: 0;
    display: none;
  }
  .vfi {
    border-top: 1px dashed #ccc;
  }
</style>
